import { useConsole, useHideLoading, useLoading } from '@/utils'
import { to } from 'await-to-js'

interface AlipayOCROptions {
  bizId: string
  type: 'FRONT' | 'BACK'
}
interface AlipayOCRRes {
  image: string
  data: {
    [x in 'name' | 'sex' | 'nationality' | 'birth' | 'num' | 'address']: {
      desc: string
      data: string
    }
  }
  array: {
    desc: string
    data: string
  }[]
  error?: Error | null
}
/** OCR识别身份证（支付宝） */
export async function useAlipayIDCardOCR(options: AlipayOCROptions) {
  // #ifdef MP-ALIPAY
  useLoading(true)
  try {
    const { readIDCard, IDCardTypes } = requirePlugin('ocr')
    const [err, res] = await to<AlipayOCRRes>(readIDCard({
      bizId: options.bizId,
      type: options.type === 'FRONT' ? IDCardTypes.FRONT : IDCardTypes.BACK,
    }))
    useHideLoading()
    if (err) {
      useConsole?.error('useIDCardOCR:alipay:to.err', err)
      return Promise.reject(err)
    }
    useConsole?.log('useIDCardOCR:alipay', res)
    if (res.error) {
      return Promise.reject(res.error)
    }
    return res
  }
  catch (error) {
    useHideLoading()
    useConsole?.error('useIDCardOCR:alipay:try.err', error)
    return Promise.reject(error)
  }
  // #endif
}
